package video

import (
	// "github.com/go-martini/martini"
	// "github.com/martini-contrib/render"
	"code.google.com/p/go.net/websocket"
	// "io/ioutil"
	// "io"
	"fmt"
	"net/http"
	"server/lib/Imartini"
	"server/lib/other"
	"strings"
	"time"
)

var img = map[string][][]byte{}

func videoServer(ws *websocket.Conn) {
	ws.SetDeadline(time.Now().Add(time.Duration(10) * time.Second)) //设置websocket超时时间，需要做心跳机制保证链接不超时
	name := ws.Request().FormValue("name")
	if name != "" {
		var err error
		websocket.Message.Send(ws, "start")
		img[name] = make([][]byte, 2)
		for {
			var reply string
			if err = websocket.Message.Receive(ws, &reply); err != nil {
				fmt.Println(err)
				break
			}
			if reply == "" {
				break
			}
			img[name][0] = img[name][1]
			img[name][1] = []byte(reply)
			ws.SetDeadline(time.Now().Add(time.Duration(10) * time.Second))
		}
	}
}

func rvideoServer(ws *websocket.Conn) {
	ws.SetDeadline(time.Now().Add(time.Duration(10) * time.Second)) //设置websocket超时时间，需要做心跳机制保证链接不超时
	name := ws.Request().FormValue("name")
	if name != "" {
		var err error
		websocket.Message.Send(ws, string(img[name][0]))
		for {
			var reply string
			if err = websocket.Message.Receive(ws, &reply); err != nil {
				fmt.Println(err)
				break
			}
			if reply == "" {
				break
			}
			websocket.Message.Send(ws, string(img[name][0]))
			ws.SetDeadline(time.Now().Add(time.Duration(10) * time.Second))
		}
	}
}

func timg(res http.ResponseWriter, req *http.Request, mlog *Imartini.Mlog) {
	res.Header().Set("Content-Type", "image/webp")
	name := req.FormValue("name")
	if name != "" && img[name][0] != nil {
		b, _ := other.Base64Decode(img[name][0][23:], "")
		res.Write(b)
	}
	// fmt.Println(img)
}

func list(res http.ResponseWriter, req *http.Request, mlog *Imartini.Mlog) {
	html := `<html><head></head>
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
<body>
%s
</body>
<script>
function chan(t){
    // alert(document.getElementById(t.id).getAttribute("src")+"&time="+new Date())
    t.href = document.getElementById(t.id).getAttribute("src")+"&time="+new Date();
}
</script>
</html>
`
	l := []string{}
	for i, _ := range img {
		l = append(l, fmt.Sprintf(`<a href="/test/video/html?name=%s">%s</a><a id="%s" onclick="chan(this)" src="/test/video/timg?name=%s" href="">（图片）</a>`, i, i, i, i))
	}
	res.Write([]byte(fmt.Sprintf(html, strings.Join(l, ""))))
}

func videohtml(res http.ResponseWriter, req *http.Request, mlog *Imartini.Mlog) {
	name := req.FormValue("name")
	html := `<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>视屏接收页面</title>
</head>
<body>
    <script type="text/javascript" src="WebP.js"></script>
    <image id="receiver" style="width:640px;height:480px" ></image>

    <script type="text/javascript" charset="utf-8">
    try{
        receiver_socket = new WebSocket("ws://www.eyuanonline.com:3333/test/video/rel?name=%s");
        var image = document.getElementById('receiver');
        var img = new Image();
        receiver_socket.onopen = function(){
        	receiver_socket.send('o');
        }
        receiver_socket.onmessage = function(data)
        {
            image.src=data.data;
            //image.getContext("2d").drawImage(img, 0, 0, image.width, image.height);
            setTimeout("receiver_socket.send('o');", 100);
        }
        receiver_socket.onclose = function(){
        	alert('网络连接已断开请重新连接');
        }
    }catch (e){
        alert(e)
    }
    // var image = document.getElementById('receiver');
    // var count = 0;
    // function set(){
    //     image.src = 'http://www.eyuanonline.com:3333/test/video/timg?name=&c='+count+'.webp';
    //     count++;
    //     image.onload = function(){
    //         setTimeout('set()', 100);
    //     }
    // }
    // set()
    </script>
</body>
</html>
`
	res.Write([]byte(fmt.Sprintf(html, name)))
	// fmt.Println(img)
}

func svideohtml(res http.ResponseWriter, req *http.Request, mlog *Imartini.Mlog) {
	name := req.FormValue("name")
	html := `<html><title>视屏上传页面</title><body>
	<!--  
    理想情况下我们应该先判断你的设备上是否  
    有摄像头或相机，但简单起见，我们在这里直接  
    写出了HTML标记，而不是用JavaScript先判断  
    然后动态生成这些标记  
    -->  
    <video id="video" width="640" height="480" autoplay></video>  
    <button  onclick="video.pause();">stop</button>
    <button  onclick="video.play();">play</button>
    <button  onclick="scamera();">拍照</button>
    <button  onclick="CatchCode();">图片编码</button>
    <canvas id="canvas" width="640" height="480" style="display:none;"></canvas>  


            
            <script type="text/javascript">
	t_socket = false;
    var socket = new WebSocket("ws://www.eyuanonline.com:3333/test/video/?name=%s");
    socket.onopen = function(){
    	t_socket = true;
        send();
    }
    socket.onclose = function(){
    	t_socket = false;
    	alert('网络连接已断开请重新连接');
    }
                // Put event listeners into place  
    window.addEventListener("DOMContentLoaded", function() {  
        // Grab elements, create settings, etc.  
        canvas = document.getElementById("canvas"),  
            context = canvas.getContext("2d"),  
            video = document.getElementById("video"),  
            videoObj = { "video": true },  
            errBack = function(error) {  
                console.log("Video capture error: ", error.code);   
            };  
      
        // Put video listeners into place  
        if(navigator.getUserMedia) { // Standard  
            navigator.getUserMedia(videoObj, function(stream) {  
                video.src = stream;  
                video.play();  
            }, errBack);  
        } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed  
            navigator.webkitGetUserMedia(videoObj, function(stream){  
                console.log(stream)
                video.src = window.webkitURL.createObjectURL(stream);  
                video.play();  
            }, errBack);  
        }  
        else if(navigator.mozGetUserMedia) { // Firefox-prefixed  
            navigator.mozGetUserMedia(videoObj, function(stream){  
                video.src = window.URL.createObjectURL(stream);  
                video.play();  
            }, errBack);  
        }  
    }, false);  
    
    function scamera(){
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
    }
    function CatchCode() {
        context.drawImage(video, 0, 0, canvas.width, canvas.height);
        //以下开始编 数据
        var imgData = canvas.toDataURL("image/WebP", 0.5);//WebP
        //将图像转换为base64数据
        // var base64Data = imgData;
        // $('#image').html(imgData);
        return imgData
    }
    function send(){
    	if(t_socket){
	        if(video.src){
	        	try{
	        		// CatchCode()
	            	socket.send(CatchCode());
	        	}catch (e){
	        		alert(e)
	        		return
	        	}
	        }
	    	setTimeout("send();", 100);
    	}
    }
            </script></body></html>
`
	res.Write([]byte(fmt.Sprintf(html, name)))
	// fmt.Println(img)
}
